
local require = require;
local ngx     = ngx;
local pairs   = pairs;
local string  = string;
local collectgarbage = collectgarbage;
local table = table;
local io = io;
local assert = assert;
local tonumber = tonumber;

local log          = require("modules.commhm.log")
local ns_time      = require("modules.commhm.time")
local uu           = require("modules.commhm.utils")
local ns_env       = require("modules.env.env")

local ns_auth_comm_checker    = require("modules.commhm.auth_comm_checker");
local gg                      = require("modules.keeper_server.keeper_gg")


local FOO = {
	_VERSION = '0.12.1',

	operations = {},
};


function FOO.do_command()
	local op_ = ngx.ctx.m_params.op
	if  FOO.operations[ op_ ] then
		FOO.operations[ op_ ]()
	else
		gg.return_table( { ret=99, msg="err_keeper_op" } )
	end
end



---按照配置文件名字，重加载对应的nginx
function FOO.operations.reload_nginx_by_config()

	if  not ngx.ctx.m_params.config_file_list then
		gg.return_table( { ret=99, msg="err_params_config_file_list" } )
		return
	end

	local t_ = uu.split( ngx.ctx.m_params.config_file_list, "," )
	--openresty_skin_1.conf
	--openresty_mult_lang_map_1.conf

	local msg_ = ""

	for i=1, #t_ do
		if  #t_[i] > 1 then

			msg_ = msg_ .. "=========================重加载模块：" .. t_[i] .. "=================\n"

			---检查这个文件是否存在
			local file_path_ = "/usr/local/openresty/nginx/conf/" .. t_[i]
			if  uu.file_exist( file_path_ ) then
				log.debug_list( "find config ok:" ..t_[i] )

				---重启对应配置文件的nginx
				local cmd_ = "cd /usr/local/openresty/nginx/; sbin/nginx -c conf/" .. t_[i] .. " -s reload;"

				if  ngx.ctx.m_params.confirm == '1' then
					uu.os_exec_async( cmd_ )
				else
					msg_ = msg_ .. "dry run no confirm:" .. cmd_ .. '\n'
				end

				ngx.sleep(0.5)
			else
				msg_ = msg_ .. "config not find:\n"
			end

		end
	end


	ngx.sleep(1)
	msg_ = msg_ .. "==================刷新nginx 列表============================\n"
	for i=1, #t_ do
		if  #t_[i] > 1 then
			---检查这个文件是否存在
			local file_path_ = "/usr/local/openresty/nginx/conf/" .. t_[i]
			if  uu.file_exist( file_path_ ) then
				---检查是否重启完毕
				local msg_one_ = gg.getOrInfoByConfigName( t_[i] )
				msg_ = msg_ .. "==加载后:\n" .. msg_one_ .. '\n'
			else
				msg_ = msg_ .. "config not find:\n"
			end
		end
	end

	gg.return_table( { ret=0, msg=msg_ } )

end



---按照配置文件名字，获得nginx的列表
function FOO.operations.get_nginx_list()

	if  not ngx.ctx.m_params.config_file_list then
		gg.return_table( { ret=99, msg="err_params_config_file_list" } )
		return
	end

	local t_ = uu.split( ngx.ctx.m_params.config_file_list, "," )
	--openresty_skin_1.conf
	--openresty_mult_lang_map_1.conf

	local msg_ = "==================刷新nginx 列表============================\n"
	for i=1, #t_ do
		if  #t_[i] > 1 then
			---检查这个文件是否存在
			local file_path_ = "/usr/local/openresty/nginx/conf/" .. t_[i]
			if  uu.file_exist( file_path_ ) then
				log.debug_list( "find config ok:" .. t_[i] )
				local msg_one_ = gg.getOrInfoByConfigName( t_[i] )
				msg_ = msg_ .. "==加载后:\n" .. uu.to_str(msg_one_) .. '\n'
			else
				msg_ = msg_ .. "config not find:\n"
			end
		end
	end


	gg.return_table( { ret=0, msg=msg_ } )

end


---同步指定模块的模块代码 (dry run 只比较差异)
function FOO.operations.rsync_code_dry()
	ngx.ctx.rsync_dry_run = 1
	FOO.operations.rsync_code()
end


---同步指定模块的模块代码
function FOO.operations.rsync_code()
	---查看密码文件是否存在
	local password_file_ = "/home/rsync_132.secrets_lua_code_r"
	if  uu.file_exist( password_file_ ) then
		---文件已经存在
		log.debug( "code file existed." )
	else
		log.debug( "create new code file." )
		uu.os_exec( "echo miniw_lua_config_ly907_read_132 > " .. password_file_ )
		uu.os_exec( "chmod 600 " .. password_file_ )
	end

	---同步代码
	if  not ngx.ctx.m_params.modules_list then
		gg.return_table( { ret=99, msg="err_params_modules_list" } )
		return
	end

	local msg_ = ""
	local t_ = uu.split( ngx.ctx.m_params.modules_list, "," )
	for i=1, #t_ do
		if  #t_[i] > 1 then
			local code_path_ = t_[i] .. '/'

			local dry_run_ = ''
			if  ngx.ctx.rsync_dry_run == 1 then
				msg_ = msg_ .. "========= dry-run (只比较代码差异) ==== lua/" .. code_path_ .. "\n"
				dry_run_ = ' --dry-run'
			else
				msg_ = msg_ .. "========= 更新代码 ==== lua/" .. code_path_ .. "\n"
			end

			local rsync_dir_name_ = gg.get_code_rsync_name( code_path_, ns_env.debug )

			if  uu.file_exist(  "lua/" .. code_path_ ) then
				local cmd_ = "rsync --progress --port=8873 -ptvr" .. dry_run_
						.. rsync_dir_name_ .. "/lua/" .. code_path_
						.. " /usr/local/openresty/nginx/lua/" .. code_path_
						.. " --password-file " .. password_file_

				-- msg_ = msg_ ..'[ ' .. rsync_dir_name_ .. "/lua/" .. code_path_ .. " ]\n"

				msg_ = msg_ ..'ret=[ ' .. uu.to_str(uu.os_exec( cmd_ )) .. " ]\n"
			else
				msg_ = msg_ .. "ERROR: 此目录不存在，请在服务器上建立一个空目录：lua/" .. code_path_ .. "\n"
			end
		end
	end

	if  not (ngx.ctx.rsync_dry_run == 1) then
		msg_ = msg_ .. "最后更新的10个文件：\n"
				.. uu.os_exec( 'find /usr/local/openresty/nginx/lua/ -name "*.lua" | xargs ls -trl | tail -n 10' )
	end

	gg.return_table( { ret=0, msg=msg_ } )

end



---只有132机器可以执行这个命令(其他机器没有这个目录)
function FOO.operations.press_pull_git()
	---check cd
	if  not uu.check_server_time_interval( "keeper_press_pull_git", 5 ) then
		gg.return_table( { ret=1, msg="调用太频繁，每5秒可以调用一次" } )
		return
	end

	local msg_ = "pull ---- miniw_activity ----\n"
    local cmd_ = "cd /home/samba/haima/code/miniw_activity/env1/; git pull;"
    msg_ = msg_ .. uu.os_exec( cmd_ ) .. "\n"

	msg_ = msg_ .. "pull ---- miniw_room ----\n"
	local cmd_ = "cd /home/samba/haima/code/miniw_room/; git pull;"
	msg_ = msg_ .. uu.os_exec( cmd_ ) .. "\n"

	---最后更新的代码
	msg_ = msg_ .. "最后更新的20个文件：\n"
			.. uu.os_exec( 'cd /home/samba/haima/code/; '
			.. 'find miniw_activity/env1/ miniw_room/ -name "*.lua" | xargs ls -trl | tail -n 20' )

    gg.return_table( { ret=0, msg=msg_ } )
end



---检查or存活状态
function FOO.operations.check_alive_or()

	local nginx_cmd_list_
	local lua_modules_

	if  ngx.ctx.m_params.or_detail == '1' then
		---通过扫描master进程，扫描查看这台机器上有多少OR在运行
		local cmd_ = "ps -ef | grep 'master process' | grep sbin/nginx | awk -F'process ' '{print $2}' | sort"
		local msg_ = uu.os_exec( cmd_ )

		lua_modules_    = gg.load_lua_modules_update()

		nginx_cmd_list_ = {}

		local t_ = uu.split( msg_, '\n' )
		for i=1, #t_ do
			if  string.sub( t_[i], 1, 10 ) == 'sbin/nginx' then
				local cmd_ = {}
				cmd_.start_cmd = t_[i]
				cmd_.name = gg.private_getShortName( t_[i] )
				if  cmd_.name then
					if  uu.file_exist( "conf/" .. cmd_.name ) then
						nginx_cmd_list_[ #nginx_cmd_list_ + 1 ] = cmd_
					end
				end
			end
		end
	end


	local fret_ = { ret=0, msg="ok",
					nginx_list = nginx_cmd_list_,
					env        = ns_env.debug,
					hostname   = gg.hostname,
					keeper_ver = gg.keeper_ver,
					modules    = lua_modules_,
	}

	if  nginx_cmd_list_ then
		fret_.nginx_list = nginx_cmd_list_
	end

	gg.return_table( fret_ )
end


return FOO;
